<template>
  <div class="login">
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="80px">

      <el-form-item label="用户名" prop="phone">
        <el-input v-model="form.phone" autocomplete="off"></el-input>
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="form.password" autocomplete="off"></el-input>
      </el-form-item>

      <el-button type="primary" @click="submitForm">提交</el-button>

    </el-form>
  </div>
</template>

<style lang="scss" scoped>
  .login {
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;

    .el-form {
      background-color: #fff;
      width: 300px;
      padding: 20px;
      border-radius: 10px;
    }

    .el-button {
      width: 100px;
      margin-left: 50%;
      transform: translateX(-50%);
    }
  }
</style>

<script>
  import { login } from '@/services/user'

  export default {
    name: 'login',
    data() {
      return {
        form: {
          phone: '18201288771',
          password: '111111',
        },
        rules: {
          phone: [
            { required: true, message: '请输入手机号', trigger: 'blur' },
            { pattern: /^1\d{10}$/, message: '请输入正确的手机号', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 18, message: '密码长度为 6 到 18 个字符', trigger: 'blur' }
          ],
        }
      }
    },
    methods: {
      async submitForm() {
        try {
          await this.$refs.form.validate()
          const data = await login(this.form)
          if (data.state !== 1) {
            return this.$message('手机号或密码错误')
          }

          // 请求成功之后
          this.$store.commit('setUser', data.content)
          this.$message({
            message: '登录成功',
            type: 'success'
          })
          this.$router.push(this.$route.query.redirect || '/')
        } catch (err) {
          this.$message('手机号或密码错误')
        }
      }
    }
  }
</script>
